import { useEffect, useState } from 'react'

const getDefaultStorage = (key: string) => {
  const data = localStorage.getItem(key)
  if (data) {
    return localStorage.getItem(key)
  }
  return undefined
}
const useStorage = (key: string, initialValue?: any): [string | undefined, (arg: string) => void, () => void] => {
  const [storedValue, setStoredValue] = useState(getDefaultStorage(key) || initialValue)
  const setStorageValue = (value: string) => {
    localStorage.setItem(key, value)
    if (value !== storedValue) {
      setStoredValue(value)
    }
  }
  const removeStorage = () => {
    localStorage.removeItem(key)
  }
  useEffect(() => {
    const data = localStorage.getItem(key)
    data && setStorageValue(data)
  }, [])

  useEffect(() => {
    const storageValue = localStorage.getItem(key)
    if (storageValue) {
      setStoredValue(storageValue)
    }
  }, [])

  return [storedValue, setStorageValue, removeStorage]
}

export default useStorage
